package hc.trip.airticket.result;

import hc.trip.airticket.bean.FlightInfo;
import hc.trip.airticket.bean.PriceInfo;
import hc.trip.airticket.bean.QueryInfo;
import hc.trip.airticket.bean.ResultInfo;
import hc.trip.airticket.constant.StaticParameter;
import hc.trip.airticket.httpclient.HttpRequestProxy;
import hc.trip.airticket.httpclient.JsonUtil;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.Cookie;
import net.sf.json.JSONObject;
/**
 * 分析海南航空
 * @author 0707
 * @date 2011-3-5
 * @description TODO
 */
public class GetFlightListHU {
      
	   private static String sessionid = "";
	   HttpRequestProxy proxy = new HttpRequestProxy();
	   ResultInfo resultInfo = null;
	/**
	 * 根据航班的查询条件（出发城市、到达城市、时间）请求并分析得到结果集合
	 * @param queryInfo
	 * @return
	 * @throws Exception
	 */
		public ResultInfo getResultInfo(QueryInfo queryInfo){
			
			//查询条件不合法
			if(queryInfo==null||queryInfo.getDateString()==null||queryInfo.getDateString().length()<=0||queryInfo.getDesCity()==null||queryInfo.getDesCity().length()<=0||queryInfo.getOrgCity()==null||queryInfo.getOrgCity().length()<=0){
				return null;
			}
			
			 
			Map postData   = new HashMap();
			Map header     = new HashMap();
			String responseText = "";
			ResultInfo resultInfo = null;
			
			//请求头部
			header.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");
		    //使用POST请求，赋值post数据
            header.put("Referer", "http://hnair.travelsky.com/huet/bc10waiting.do");
			postData.put("orgCity", queryInfo.getOrgCity());  //出发机场
			postData.put("dstCity", queryInfo.getDesCity());  //到达机场
			postData.put("adultNum", "1");  //成人数
			postData.put("childNum", "0");  //儿童数
			postData.put("iscalendar", "true");  // 
			postData.put("queryPassengerType", "0");  // 
			postData.put("returnDate", "");  //返回日期
			postData.put("takeoffDate", queryInfo.getDateString()); //出发日期
			postData.put("tripType", "ONEWAY");  //单程
			postData.put("type", "on"); 
	 
			 try { 
				 responseText = proxy.doRequest(
					 	    "http://hnair.travelsky.com/huet/bc10_av.do", postData, header,"GBK");
				resultInfo = (ResultInfo)analyzeResopnseText(responseText);
				}
		        catch (ConnectTimeoutException e) {   //超时
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusTimeOut);   
				e.printStackTrace();
			} 
		        catch (Exception e) {                //其他异常
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusError);
				e.printStackTrace();
			}
		  	return resultInfo;
			 
		}
		
		
		/**
		 * 根据国航网站返回的responseText通过正则表达式分析出结果
		 * @param source  返回的responseText
		 * @return        结果列表 
		 * @throws Exception 
		 */
		public ResultInfo analyzeResopnseText(String source) throws Exception{
		      PriceInfo priceInfo = null;
		      List priceList  =  null;
		      ResultInfo resultInfo = new ResultInfo();  //结果对象
	 		  String[] parts = source.split("<tr class=\"tbody\">"); //将每一个航班区分开来

			     String[] airPort = new String[2];  //出发机场和目的机场
			     ArrayList<FlightInfo> flightInfos = new ArrayList<FlightInfo>();  //存放所有的航班信息
			     

			     StringBuffer regexSB = new StringBuffer();  //匹配航班信息
			     
			     regexSB.append("<td>(.*?)</td>\\s*"); 
			     regexSB.append("<td mark=\"order_time\"><img src=\"/huet/bc10/static/images/icon_time\\.gif\" />(.*?)&nbsp;&nbsp;");
			     regexSB.append("<img src=\"/huet/bc10/static/images/icon_time\\s*red.gif\" />(.*?)</td>\\s*");
			     regexSB.append("<td>(.*?)</td>\\s*<td>(.*?)</td>");
			    
			     
			     String regex =regexSB.toString();
			     String priceRegex = "";
			     String price1Regex = ""; //匹配舱位信息
			     priceRegex = "<td cabin='(\\w)\\|(.*?)\\|(.*?)'>\\s*<span style=\"margin-top: 0px\"> <input name=\"segpay_memb_radio\" type=\"radio\" value=\"(.*?)&\\w{1}\"\\s*pricedisplay=\".*?\"\\s*/>\\s*<span>";
			     price1Regex ="<h1>舱位</h1>\\s*<h2>产品</h2>\\s*</div>\\s*</div>\\s*<div class=\"right\">\\s*<ul.*?>(.*?)</ul>\\s*</div>";
			     Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
			     Pattern pPrice = Pattern.compile(priceRegex,Pattern.CASE_INSENSITIVE);
			     Pattern p1Price = Pattern.compile(price1Regex,Pattern.CASE_INSENSITIVE);
     		     FlightInfo tempInfo = null;
    		     double  tempMinPriceForAll = 0.0;  //所有航班的最低价格
    		     double  tempMaxPriceForAll = 0.0;  //所有航班的最高价格
    		     boolean tempIsFirstForAll = true;
     		     //依次取出每个航班的信息,因为parst[0]中没有航班信息，所以数组下标从1开始
 		     	 for(int j=1;j<parts.length;j++){
 				 priceList  =  new ArrayList();
 				 tempInfo =new FlightInfo();
			     Matcher matcher = p.matcher(parts[j]);
			      
			     if(matcher.find())   //匹配航班信息
			     {
			    	 String flightNo = matcher.group(1).trim();
			    	 // String flightNoAndShareCode = matcher.group(2).trim();
			    	 tempInfo.setFlightNo(flightNo);  //航班号
			    	 //判断是否是代码共享
 
			    	 //判断代码共享结束
			    	 tempInfo.setTakeOffTime(matcher.group(2).trim());
			    	 tempInfo.setArriveTime(matcher.group(3).trim());
			    	 tempInfo.setPlaneType(matcher.group(5).trim());
			    	 if (matcher.group(4).trim()!=null&&matcher.group(4).trim().equals("有")) {  //经停
						tempInfo.setStopOver(true);
					}
			    	 
			     }else {
					if (j==1) {
						System.out.println("没有查询到航班....");
						return null;
					}
				}
			     //匹配舱位
			     Matcher matcher1Price = p1Price.matcher(parts[j]);
			     String strTemp = "";
			     if(matcher1Price.find())   //匹配舱位信息
			     {
			    	   strTemp = matcher1Price.group(1).trim();  
			     }
		         String spaceRegex = "<li>(<b>|)(.*?)舱(</b>|)</li>";
                 Pattern spacePattern= Pattern.compile(spaceRegex);
                 Matcher spaMatcher = spacePattern.matcher(strTemp);
		    	 double tempMinPrice = 0.0;
		    	 double tempMaxPrice = 0.0;
		    	 boolean isFirst = true;
               while (spaMatcher.find()) {
                 priceInfo = new PriceInfo();
                 priceInfo.setSpace(spaMatcher.group(2).trim());
                 priceList.add(priceInfo);
                 

                 HashMap header = new HashMap();
                 HashMap jsonHashMap = new HashMap();
                 HashMap detailJsonMap = new HashMap();
                 String responseString = "";
                 header.put("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
                 header.put("Connection", "keep-alive");
                 header.put("Host","hnair.travelsky.com");
                 header.put("Accept","application/json, text/javascript, */*");
                 header.put("Referer", "http://hnair.travelsky.com/huet/bc10_av.do");
                 header.put("X-Requested-With","XMLHttpRequest");
                 String cookie = proxy.getCookieStr();
 
 
                 //header.put("Cookie", "JSESSIONID=0000aAaM177_5uawmZWmT27-iu9:11h3ce6ve");
                 // String url = "http://hnair.travelsky.com/huet/bc10_getsegmentdetail.do?agreementId=WO&&comboIndex=0&step=0&detailType=2&fltNo="+tempInfo.getFlightNo()+"&cabin="+priceInfo.getSpace();
                 String url = "http://hnair.travelsky.com/huet/bc10_getsegmentdetail.do?ajaxtimestamp="+System.currentTimeMillis()+"&detailType=2&fltNo="+tempInfo.getFlightNo()+"&cabin="+priceInfo.getSpace()+"&agreementId=WO&comboIndex=0&step=0";
                 responseString = proxy.doRequest(url,null, header, "GBK");
   
                 jsonHashMap = (HashMap)JsonUtil.getMapFromClientResoponseJsonStr(responseString);
          
                 detailJsonMap = (HashMap) JsonUtil.getMapFromClientResoponseJsonStr(jsonHashMap.get("detail"));
              if (!priceInfo.getSpace().equals(detailJsonMap.get("cabin"))) {
				 System.out.println("海航分析价格出现异常");
				 resultInfo.setStatus(StaticParameter.analyzeStatusError);
			}
              priceInfo.setRemind((String)detailJsonMap.get("refundDesc"));
                 }
                
                 //分析价格
                 String prcie2Regex = "<div class=\"left\">网站专享</div>\\s*<div class=\"right\">\\s*<ul class=\"wide no\">(.*?)</ul>\\s*</div>";
 		
                 Pattern price2Pattern = Pattern.compile(prcie2Regex);
                 Matcher price2Matcher = price2Pattern.matcher(parts[j]);
                 String prcie2String = "";
                 if(price2Matcher.find()){
                	// System.out.println(price2Matcher.group(1).trim());
                	 prcie2String = price2Matcher.group(1).trim();
                 }
                 String price3Regex = "<li>\\s*<input type=\"radio\" name=\"ticket0\"  onclick=\"setSelectNormal.*?\"/>\\s*￥(.*?)\\s*</li>";
                 Pattern price3Pattern = Pattern.compile(price3Regex);
                 Matcher price3Matcher = price3Pattern.matcher(prcie2String);
                 Iterator iterator = priceList.iterator();
                 
                 while(price3Matcher.find()&&iterator.hasNext()){
                	// System.out.println(price3Matcher.group(1));
                	PriceInfo P1 = (PriceInfo)iterator.next();
                	P1.setPrice(Double.parseDouble(price3Matcher.group(1).trim()));
               	  //一个航班不同cabin的最低和最高价格获取
			    	  if (isFirst) {
			    		  tempMinPrice = P1.getPrice();
			    		  tempMaxPrice = P1.getPrice();
			    		  tempInfo.setMinprice(tempMinPrice);
			    		  tempInfo.setMaxprice(tempMaxPrice);
			    		  isFirst = false;
					}
			    	 
			    	  //获取同一个航班的不同舱位中的最高和最低价格
					     if (tempMinPrice>P1.getPrice()) {   //如果一个航班的tempMinPrice不是最低价格
					    	 tempMinPrice = P1.getPrice();
							}
					     if (tempMaxPrice<P1.getPrice()) {   //如果一个航班的tempMaxPrice不是最高价格
					    	 tempMaxPrice = P1.getPrice(); 
						}
					     tempInfo.setMaxprice(tempMaxPrice);
					     tempInfo.setMinprice(tempMinPrice);
                 }
                 tempInfo.setPrice(priceList);
			     flightInfos.add(tempInfo);
			   //在每一个航班的循环内，取得目前航班中的最低价格和最高价格
			     if (tempIsFirstForAll) {      //初始值
			    	 tempMinPriceForAll = tempInfo.getMinprice();
			    	 tempMaxPriceForAll = tempInfo.getMaxprice();
			    	 tempIsFirstForAll  = false;
				}
			     if (tempMinPriceForAll>tempInfo.getMinprice()) {   
 
			    	 tempMinPriceForAll = tempInfo.getMinprice();
				}
			     if (tempMaxPriceForAll<tempInfo.getMaxprice()) {
				 
			    	 tempMaxPriceForAll = tempInfo.getMaxprice();
				}
		    	 resultInfo.setMinPriceFlight(tempMinPriceForAll);
		    	 resultInfo.setMaxPriceFlight(tempMaxPriceForAll);
			     
 		     	 }
				 
 		        resultInfo.setResultList(flightInfos);	   
				return resultInfo;
		}
		
		


}
 